import { Store } from "../../core";

import PrintStatus from "./PrintStatus";
import StoreProps from "./StoreProps";
import { FC, RefObject, useEffect } from "react";

interface ShortcutHandlerProps {
  containerRef: RefObject<HTMLDivElement>;
  store: Store<StoreProps>;
}

const isMac = () =>
  typeof window !== "undefined"
    ? /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)
    : false;

const ShortcutHandler: FC<ShortcutHandlerProps> = ({ containerRef, store }) => {
  const keydownHandler = (e: KeyboardEvent) => {
    if (e.shiftKey || e.altKey || e.key !== "p") {
      return;
    }

    const isCommandPressed = isMac() ? e.metaKey : e.ctrlKey;
    if (!isCommandPressed) {
      return;
    }

    const containerEle = containerRef.current;
    if (
      !containerEle ||
      !document.activeElement ||
      !document.activeElement.contains(containerEle)
    ) {
      return;
    }

    e.preventDefault();
    store.update("printStatus", PrintStatus.Preparing);
  };

  useEffect(() => {
    const containerEle = containerRef.current;
    if (!containerEle) {
      return;
    }

    document.addEventListener("keydown", keydownHandler);
    return () => {
      document.removeEventListener("keydown", keydownHandler);
    };
  }, [containerRef.current]);

  return <></>;
};

export default ShortcutHandler;
